# -*- coding: utf-8 -*-

import os,logging

from google.appengine.ext import db
from google.appengine.ext.db import Model as DBModel

logging.info('module base reloaded')

class Category(db.Model):
    name = db.StringProperty()
    parentCategory = db.SelfReferenceProperty()
    desc = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    
    def save(self):
        self.put()
    
    def delete(self):
        for book in Book.all().filter('category =', self):
            book.category = None
            book.put()
        for cat in Category.all().filter('parentCategory = ', self):
            cat.delete()
        db.Model.delete(self)
    
    @property
    def children(self):
        return [c for c in Category.all().filter('parentCategory', self)]

    @classmethod
    def allTops(self):
        return [c for c in Category.all() if not c.parentCategory]

class Press(db.Model):
    name = db.StringProperty()
    desc = db.TextProperty()
    created = db.DateTimeProperty(auto_now_add=True)
    
    def save(self):
        self.put()

    def delete(self):
        for book in Book.all().filter('press =', self):
            book.press = None
            book.put()
        db.Model.delete(self)

class Media(db.Model):
    name = db.StringProperty()
    mtype = db.StringProperty()
    bits = db.BlobProperty()
    desc = db.TextProperty()
    date = db.DateTimeProperty(auto_now_add=True)
    download = db.IntegerProperty(default=0)
    
    @property
    def size(self):
        return len(self.bits)

    def delete(self):
        for book in Book.all().filter('cover =', self):
            book.cover = None
            book.put()
            
        db.Model.delete(self)

class Book(db.Model):
    name = db.StringProperty(default='book name')
    author = db.StringProperty(default='admin')
    category = db.ReferenceProperty(Category)
    press = db.ReferenceProperty(Press)
    cover = db.ReferenceProperty(Media)
    coverStory = db.TextProperty()
    price = db.FloatProperty()
    issue = db.StringProperty()
    isbn = db.StringProperty()
    language = db.StringProperty()
    publish = db.DateTimeProperty()
    lastUpdated = db.DateTimeProperty(auto_now=True)
    created = db.DateTimeProperty(auto_now_add=True)
    
    def save(self):
        self.put()

    def delete(self):
#        media = self.cover
#        if media:
#            media.delete()
        db.Model.delete(self)

class UpdateInfo(db.Model):
    lastUpdated = db.DateTimeProperty(auto_now=True)
    version = db.FloatProperty()
    
    def save(self):
        self.version += 0.1
        self.put()
